package com.example.demo.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.Record;
import com.example.demo.common.Result;
import com.example.demo.mapper.RecordMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/source")
@Api(tags = "7、多数据源管理")
@ApiSupport(author = "罗海林", order = 7)
@Validated
@RequiredArgsConstructor
public class DataSourceController {

    private final RecordMapper recordMapper;

    @PostMapping("/test1")
    @ApiOperation(value = "访问主数据库", response = Result.class)
    @ApiOperationSupport(author = "罗海林", order = 1)
    public Result test1() {
        LambdaQueryWrapper<Record> query = new LambdaQueryWrapper<>();
        query.select(Record::getContent);
        query.eq(Record::getType, "update");

        //List<Record> list = recordMapper.selectList(query);
        List<Map<String, Object>> list = recordMapper.selectMaps(query);

        Result res = new Result();
        res.ok();
        res.put("list", list);
        return res;
    }

    @PostMapping("/test2")
    @ApiOperation(value = "访问从数据库", response = Result.class)
    @ApiOperationSupport(author = "王彦远", order = 2)
    @DS("slave_1")
    public Result test2() {
        LambdaQueryWrapper<Record> query = new LambdaQueryWrapper<>();
        query.select(Record::getType, Record::getContent);
        query.eq(Record::getType, "update");

        //List<Record> list = recordMapper.selectList(query);
        List<Map<String, Object>> list = recordMapper.selectMaps(query);

        Result res = new Result();
        res.ok();
        res.put("list", list);
        return res;
    }
}
